import tkinter as tk
from tkinter import filedialog, ttk, messagebox
import os
import sys

class FileMergerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Python文件整合工具")
        self.root.geometry("700x500")
        
        # 设置中文字体支持
        self.style = ttk.Style()
        self.style.configure("TLabel", font=("SimHei", 10))
        self.style.configure("TButton", font=("SimHei", 10))
        self.style.configure("TFrame", padding=10)
        
        # 存储选中的文件
        self.main_file = tk.StringVar()
        self.lib_files = []
        
        # 创建UI
        self.create_widgets()
    
    def create_widgets(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 1. 导入入口函数文件部分
        ttk.Label(main_frame, text="1. 选择入口函数文件:", font=("SimHei", 12, "bold")).pack(anchor=tk.W, pady=(0, 5))
        
        main_file_frame = ttk.Frame(main_frame)
        main_file_frame.pack(fill=tk.X, pady=(0, 15))
        
        ttk.Entry(main_file_frame, textvariable=self.main_file, width=50).pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
        ttk.Button(main_file_frame, text="浏览...", command=self.select_main_file).pack(side=tk.RIGHT)
        
        # 2. 选择依赖库文件部分
        ttk.Label(main_frame, text="2. 选择依赖库文件:", font=("SimHei", 12, "bold")).pack(anchor=tk.W, pady=(0, 5))
        
        lib_files_frame = ttk.Frame(main_frame)
        lib_files_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 15))
        
        self.lib_files_listbox = tk.Listbox(lib_files_frame, selectmode=tk.EXTENDED, width=70, height=10)
        self.lib_files_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        scrollbar = ttk.Scrollbar(lib_files_frame, orient=tk.VERTICAL, command=self.lib_files_listbox.yview)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.lib_files_listbox.config(yscrollcommand=scrollbar.set)
        
        buttons_frame = ttk.Frame(main_frame)
        buttons_frame.pack(fill=tk.X, pady=(0, 15))
        
        ttk.Button(buttons_frame, text="添加文件...", command=self.add_lib_files).pack(side=tk.LEFT, padx=(0, 10))
        ttk.Button(buttons_frame, text="移除选中", command=self.remove_lib_files).pack(side=tk.LEFT)
        
        # 3. 整合按钮
        ttk.Button(main_frame, text="整合为单个文件", command=self.merge_files, style="Accent.TButton").pack(pady=20)
        
        # 状态标签
        self.status_var = tk.StringVar(value="请选择文件进行整合")
        ttk.Label(main_frame, textvariable=self.status_var, foreground="blue").pack(side=tk.BOTTOM, pady=10)
    
    def select_main_file(self):
        """选择入口函数文件"""
        file_path = filedialog.askopenfilename(
            title="选择入口函数文件",
            filetypes=[("Python文件", "*.py"), ("所有文件", "*.*")]
        )
        if file_path:
            self.main_file.set(file_path)
            self.status_var.set(f"已选择入口文件: {os.path.basename(file_path)}")
    
    def add_lib_files(self):
        """添加依赖库文件"""
        file_paths = filedialog.askopenfilenames(
            title="选择依赖库文件",
            filetypes=[("Python文件", "*.py"), ("所有文件", "*.*")]
        )
        
        for file_path in file_paths:
            if file_path not in self.lib_files and file_path != self.main_file.get():
                self.lib_files.append(file_path)
                self.lib_files_listbox.insert(tk.END, os.path.basename(file_path))
        
        if file_paths:
            self.status_var.set(f"已添加 {len(file_paths)} 个依赖文件")
    
    def remove_lib_files(self):
        """移除选中的依赖库文件"""
        selected_indices = sorted(self.lib_files_listbox.curselection(), reverse=True)
        if not selected_indices:
            messagebox.showinfo("提示", "请先选择要移除的文件")
            return
        
        for index in selected_indices:
            self.lib_files_listbox.delete(index)
            del self.lib_files[index]
        
        self.status_var.set(f"已移除 {len(selected_indices)} 个文件")
    
    def merge_files(self):
        """将所有选中的文件整合为单个文件"""
        if not self.main_file.get():
            messagebox.showerror("错误", "请先选择入口函数文件")
            return
        
        if not self.lib_files:
            if messagebox.askyesno("提示", "未选择依赖库文件，仅导出入口文件吗？"):
                # 只处理入口文件
                pass
            else:
                return
        
        # 选择保存位置
        save_path = filedialog.asksaveasfilename(
            title="保存整合文件",
            defaultextension=".py",
            filetypes=[("Python文件", "*.py"), ("所有文件", "*.*")]
        )
        
        if not save_path:
            return
        
        try:
            # 开始整合文件
            with open(save_path, 'w', encoding='utf-8') as outfile:
                # 写入文件整合说明
                outfile.write("# 整合后的Python文件\n")
                outfile.write(f"# 生成时间: {self.get_current_time()}\n")
                outfile.write(f"# 包含文件: {os.path.basename(self.main_file.get())}")
                for lib_file in self.lib_files:
                    outfile.write(f", {os.path.basename(lib_file)}")
                outfile.write("\n\n")
                
                # 先写入所有依赖库文件
                for lib_file in self.lib_files:
                    outfile.write(f"# 开始: {os.path.basename(lib_file)}\n")
                    with open(lib_file, 'r', encoding='utf-8') as infile:
                        outfile.write(infile.read())
                    outfile.write(f"\n# 结束: {os.path.basename(lib_file)}\n\n")
                
                # 最后写入入口函数文件
                outfile.write(f"# 开始: {os.path.basename(self.main_file.get())} (入口文件)\n")
                with open(self.main_file.get(), 'r', encoding='utf-8') as infile:
                    outfile.write(infile.read())
                outfile.write(f"\n# 结束: {os.path.basename(self.main_file.get())}\n")
            
            self.status_var.set(f"文件已成功整合至: {save_path}")
            messagebox.showinfo("成功", f"文件已成功整合至:\n{save_path}")
            
        except Exception as e:
            self.status_var.set(f"整合失败: {str(e)}")
            messagebox.showerror("错误", f"整合文件时发生错误:\n{str(e)}")
    
    def get_current_time(self):
        """获取当前时间字符串"""
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

if __name__ == "__main__":
    # 确保中文显示正常
    root = tk.Tk()
    app = FileMergerApp(root)
    root.mainloop()